﻿using ZQNB.AppLib.Cloud.Models;
using ZQNB.BaseLib.Core;
using ZQNB.Common;
using ZQNB.Common.Caching;
using ZQNB.Common.Models;

namespace ZQNB.AppLib.Cloud.Helpers
{
    /// <summary>
    /// 云中心使用Session实现的认证帮助类
    /// </summary>
    public class CloudMembershipHelper : ICloudMembershipHelper
    {
        private readonly ICloudAccountService _cloudAccountService;
        private readonly IPerSessionCacheManager _perSessionCacheManager;

        public CloudMembershipHelper(ICloudAccountService cloudAccountService, IPerSessionCacheManager perSessionCacheManager)
        {
            _cloudAccountService = cloudAccountService;
            _perSessionCacheManager = perSessionCacheManager;
        }

        private const string CurrentCloudUserKey = "CurrentCloudUser";
        public MessageResult Login(CloudAccountLogon loginVo)
        {
            MessageResult mr = new MessageResult();
            bool isOK  = _cloudAccountService.Validate(loginVo.UserName, loginVo.Password);
            if (isOK)
            {
                _perSessionCacheManager.Set(CurrentCloudUserKey, loginVo.UserName);
                mr.Message = "验证成功";
                return mr;
            }

            mr.Message = "验证失败";
            return mr;
        }

        public void Logout()
        {
            _perSessionCacheManager.Remove(CurrentCloudUserKey);
        }

        public MessageResult ChangePassword(CloudAccountChangePassword changePass)
        {
            MessageResult mr = new MessageResult();
            if (changePass.NewPassword != changePass.ConfirmPassword)
            {
                mr.Success = false;
                mr.Message = "两次输入密码不匹配";
                return mr;
            }

            string identityName = GetCurrentIdentity();
            bool isOk = _cloudAccountService.ChangePassword(
                identityName,
                changePass.OldPassword,
                changePass.NewPassword);

            mr.Success = isOk;
            mr.Message = isOk ? "修改成功" : "修改失败";

            return mr;
        }

        public bool IsCurrentLogin()
        {
            return !string.IsNullOrWhiteSpace(GetCurrentIdentity());
        }

        public string GetCurrentIdentity()
        {
            string username =  _perSessionCacheManager.Get<string>(CurrentCloudUserKey);
            return username;
        }
    }
}
